﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Idenmpotency
{
    /// <summary>
    /// 基于内存字典的
    /// </summary>
    public class IdenmpotencyRequestRepositroyMemoryDictionary: IIdenmpotencyRequestRepositroy
    {
        /// <summary>
        /// 缓存
        /// </summary>
        private IDictionary<string, IIdenmpotencyRequest> _cache = new ConcurrentDictionary<string, IIdenmpotencyRequest>();
        /// <summary>
        /// 保存请求
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        /// <exception cref="IdenmpotencyException"></exception>
        public async Task SaveAsync(IIdenmpotencyRequest request)
        {
            await Task.Yield();
            try
            {
                _cache.Add(request.Key, request);
            }
            catch (Exception e)
            {
                throw new IdenmpotencyException($"幂等性请求保存错误-{e.Message}");
            }
            
        }
        /// <summary>
        /// 请求是否存在
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        /// <exception cref="IdenmpotencyException"></exception>
        public async Task<bool> IsExistAscyn(IIdenmpotencyRequest request)
        {
            try
            {
                bool result = this._cache.ContainsKey(request.Key);
                return await Task.FromResult<bool>(result);
            }
            catch (Exception e)
            {
                throw new IdenmpotencyException($"幂等性请求检查错误-{e.Message}");
            }
        }
    }
}
